import tool from './tool'
import axios from 'axios';
import md5 from 'js-md5';
var Mint = require("mint-ui");
var _this = this;
var AccessKey = "csbr0000";
const ajaxMethod = {
  ajax: function (type, method, param) {
    Mint.Indicator.open();
    // var param = Object.assign(param,{
    // 	method:method,
    // 	v:1000,
    // 	timestamp:tool.getDate(new Date().getTime(), 'yyyy-MM-dd hh:mm:ss')
    // });
    return axios({
      headers: {},
      method: 'get',
      url: process.env.API_ROOT + '/drugcloud_api/' + method,
      params: param
    }).then((response) => {
      Mint.Indicator.close();
      return response.data;
    }).catch((error) => {
      console.log('get请求失败:', error);
      Mint.Indicator.close();
      errProcess(error);
    });
  },
  ajaxPost: function (type, method, param, loadtxt) {
    var loadtxts = loadtxt || ''
    Mint.Indicator.open(loadtxts);
    // var param = Object.assign(param,{
    //   method:method,
    //   v:1000,
    //   timestamp:tool.getDate(new Date().getTime(), 'yyyy-MM-dd hh:mm:ss')
    // });

    if (localStorage.userinfo == null || localStorage.userinfo == '') {
      return axios({
        headers: {
          "Content-type": "application/json"
        },
        method: 'post',
        url: process.env.API_ROOT + '/drugcloud_api/' + method,
        data: param
      }).then((response) => {
        // console.log(response.data, "@@")
        Mint.Indicator.close();
        return response.data;
      }).catch((error) => {
        console.log('post请求失败:', error);
        Mint.Indicator.close();
        errProcess(error);
      });
    } else {
      var userinfo = JSON.parse(localStorage.userinfo);
      var access_token = userinfo.token;
      return axios({
        headers: {
          "Content-type": "application/json"
        },
        method: 'post',
        url: process.env.API_ROOT + '/drugcloud_api/' + method + '?access_token=' + access_token,
        data: param
      }).then((response) => {
        // console.log(response.data, "@@")
        Mint.Indicator.close();
        return response.data;
      }).catch((error) => {
        console.log('post请求失败:', error);
        Mint.Indicator.close();
        errProcess(error);
      });
    }

  }
}
//输出接口请求方法
export default {
  get: function (method, param) {
    return ajaxMethod.ajax('get', method, param)
  },
  post: function (method, param, loadtxt) {
    return ajaxMethod.ajaxPost('post', method, param, loadtxt)
  }
}

function errProcess(error) {
  var errCode = error.response.status,
    apiName = error.response.config.url.replace("/drugcloud_api/", ""),
    printErr = "";
  switch (errCode) {
    case 403:
      printErr = '非法接口调用，拒绝访问'
      break

    case 404:
      printErr = apiName + ' 接口不存在'
      break

    case 500:
      printErr = '内部服务器错误，请联系管理员'
      break

    case 504:
      printErr = '网络错误，请检查是否已联网'
      break

    default:
      printErr = '未知错误';
  }
  Mint.Toast(printErr);
}